package com.hotel.service;

import com.hotel.entity.Room;
import com.hotel.repository.RoomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service("roomService")
public class RoomService {

    private final RoomRepository repository;

    @Autowired
    public RoomService(RoomRepository repository) {
        this.repository = repository;
    }

    public Room updateRoom(Long id, Room updatedRoom) {
        Integer roomId = id.intValue();

        Optional<Room> existingRoomOptional = repository.findById(roomId);

        if (existingRoomOptional.isPresent()) {
            Room existingRoom = existingRoomOptional.get();

            if (updatedRoom.getRoom_number() != null && !updatedRoom.getRoom_number().isEmpty()) {
                existingRoom.setRoom_number(updatedRoom.getRoom_number());
            }
            if (updatedRoom.getRoom_type() != null && !updatedRoom.getRoom_type().isEmpty()) {
                existingRoom.setRoom_type(updatedRoom.getRoom_type());
            }
            if (updatedRoom.getBeds() != null) {
                existingRoom.setBeds(updatedRoom.getBeds());
            }
            if (updatedRoom.getPrice() != null) {
                existingRoom.setPrice(updatedRoom.getPrice());
            }
            if (updatedRoom.getStatus() != null && !updatedRoom.getStatus().isEmpty()) {
                existingRoom.setStatus(updatedRoom.getStatus());
            }

            repository.update(existingRoom);
            return existingRoom;
        } else {
            throw new RuntimeException("Room not found with id: " + id);
        }
    }

    // 修正后的 deleteRoom 方法
    public void deleteRoom(Long id) {
        Integer roomId = id.intValue();

        Optional<Room> roomToDeleteOptional = repository.findById(roomId);
        // 【修正】将 isEmpty() 替换为 !isPresent()
        if (!roomToDeleteOptional.isPresent()) { //
            throw new RuntimeException("Room not found with id: " + id);
        }

        Room roomToDelete = roomToDeleteOptional.get();
        if ("已入住".equals(roomToDelete.getStatus())) {
            throw new RuntimeException("Cannot delete room " + id + " because it is currently occupied.");
        }

        repository.delete(roomId);
    }


    public void save(Room room) {
        if (room.getStatus() == null || room.getStatus().isEmpty()) {
            room.setStatus("空闲");
        }
        repository.save(room);
    }

    public List<Room> findAll() {
        return repository.findAll();
    }

    public void delete(Integer roomId) {
        repository.delete(roomId);
    }

    public void update(int id, Room room) {
        room.setRoom_id(id);
        repository.update(room);
    }

    public List<Room> findAvailableRooms(){
        return repository.findAvailableRooms();
    }
}